<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :showOkBtn="false"
    :okAuth="'wh:pd:whPdStock:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    @close="handleCancel"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #queryButton>
        <div class="text-right" v-if="record.pdStatus === '0' || record.isNewRecord">
          <a-button type="primary" :loading="queryLoading" @click="handleQuery">
            {{ t('查询') }}
          </a-button>
        </div>
      </template>
    </BasicForm>

    <!-- 查询结果表格 v-if="showQueryTable"-->
    <div class="mt-4">
      <h3 class="mb-2">{{ t('盘点明细') }}</h3>
      <BasicTable
        @register="registerWhPdStocksTable"
        :canResize="false"
        :showTableSetting="false"
      />
    </div>

    <!-- 明细抽屉 -->
    <DetailDrawer @register="registerDetailDrawer" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWhPdWhPdStockForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner, useDrawer } from '/@/components/Drawer';
  import { WhPdStockPosBill, whPdStockPosBillForm, whPdStockPosBillSave, saveByType, whPdStockPosBillsListData } from '/@/api/wms/wh/pd/whPdStockPosBill';
  import { whPdStockPosBillsInvListData } from '/@/api/wms/wh/pd/whPdStockPosBillsInv';
  import DetailDrawer from './detailDrawer.vue';
  import { companyTreeData } from '/@/api/sys/company';
  import { useUserStore } from '/@/store/modules/user';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { basPositionTreeData } from '/@/api/bas/pos/basPosition';
  import { useDict } from '/@/components/Dict';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wh.pd.whPdStockPosBill');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WhPdStockPosBill>({} as WhPdStockPosBill);
  const showQueryTable = ref(false);
  const userStore = useUserStore();
  const pdTypeOptions = ref<any[]>([]);
  const queryLoading = ref(false);
  const page = ref(20);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: (record.value as any).isNewRecord ? t('新增盘点单') : t('编辑盘点单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'companyCode',
      fieldLabel: 'company.companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
        immediate: true,
      },
      required: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
      },
      required: true,
    },
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    // {
    //   label: t('备注'),
    //   field: 'fexplanation',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 255,
    //   },
    // },
    {
      label: t('公司编码'),
      field: 'companyCode',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
      show: false,
    },
    {
      label: t('盘点方式'),
      field: 'pdType',
      component: 'Select',
      componentProps: {
        maxlength: 64,
        allowClear: true,
        options: pdTypeOptions,
        onChange: (value: string) => {
          // 当盘点方式改变时，如果不是1则清空货位字段
          if (value !== '1') {
            const currentValues = getFieldsValue();
            setFieldsValue({
              ...currentValues,
              posCode: '',
              posName: '',
            });
          }
        },
      },
      defaultValue: '2',
      required: true,
    },
    {
      label: t('仓库'),
      field: 'whcode',
      fieldLabel: 'basWare.cwhname',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        onChange: (_value: string) => {
          // 当仓库改变时，清空货位字段的值
          const currentValues = getFieldsValue();
          setFieldsValue({
            ...currentValues,
            posCode: '',
            posName: '',
          });
        },
      },
      required: true,
    },
    {
      label: t('单据状态'),
      field: 'status',
      component: 'Select',
      componentProps: {
        maxlength: 64,
        dictType: 'wms_pd_zf_status',
      },
      dynamicDisabled: true,
    },
    {
      label: t('货位'),
      field: 'posCode',
      fieldLabel: 'posName',
      component: 'ListSelect',
      componentProps: ({ formModel }) => {
        const hasWarehouse = formModel?.whcode;
        return {
          checkbox: true,
          selectType: 'posSelect',
          queryParams: hasWarehouse ? { whcode: formModel.whcode } : {},
          disabled: !hasWarehouse,
          placeholder: hasWarehouse ? '请选择货位' : '请先选择仓库',
        };
      },
      show: ({ values }) => {
        // 只有盘点方式为1时才显示货位字段
        return values.pdType === '1';
      },
      required: ({ values }) => {
        // 只有盘点方式为1时货位字段才必填
        return values.pdType === '1';
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('总数'),
      field: 'iqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      dynamicDisabled: true,
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('实盘总数'),
      field: 'sumqty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
      },
      dynamicDisabled: true,
      rules: [{ pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') }],
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: '',
      field: 'queryButton',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'queryButton',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, getFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  // 明细抽屉
  const [registerDetailDrawer] = useDrawer();

  const [registerWhPdStocksTable, whPdStocksTable] = useTable({
    api: whPdStockPosBillsInvListData, // 恢复API配置以正确处理otherData
    immediate: false, // 不立即加载数据
    beforeFetch: (params: any) => {
      console.log('beforeFetch 被调用，当前 record.value:', record.value);

      // 如果是新增记录，阻止API调用
      // if (record.value && (record.value as any).isNewRecord) {
      //   console.log('新增记录，阻止 whPdStockPosBillsInvListData API 调用');
      //   return false; // 返回 false 阻止API调用
      // }

      // 如果没有 djno，阻止API调用
      if (!record.value || !record.value.djno) {
        console.log('没有 djno，阻止 whPdStockPosBillsInvListData API 调用');
        return false; // 返回 false 阻止API调用
      }

      // 添加单据号参数
      const result = {
        ...params,
        'parent.djno.djno': record.value.djno,
      };
      console.log('允许 API 调用，参数:', result);
      return result;
    },
    columns: [
      {
        title: t('单据号'),
        dataIndex: 'parent.djno.djno',
        width: 130,
        align: 'left',
      },
      {
        title: t('商品编码'),
        dataIndex: 'basInv.viewCode',
        key: 'inv.inv_code',
        sorter: true,
        width: 150,
        align: 'left',
      },
      {
        title: t('商品名称'),
        dataIndex: 'basInv.invName',
        key: 'inv.inv_name',
        sorter: true,
        width: 270,
        align: 'left',
      },
      {
        title: t('货位'),
        dataIndex: 'parent.basPosition.posCode',
        width: 130,
        align: 'left',
      },
      {
        title: t('货位名称'),
        dataIndex: 'parent.basPosition.posName',
        width: 130,
        align: 'left',
      },
      {
        title: t('账存数'),
        dataIndex: 'iqty',
        width: 130,
        align: 'left',
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('实盘数'),
        dataIndex: 'frealqty',
        width: 130,
        align: 'left',
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('盈亏数'),
        dataIndex: 'fqty',
        width: 130,
        align: 'left',
        showSummary: true,
        showTotalSummary: true,
      },
      {
        title: t('盘点状态'),
        dataIndex: 'parent.pdStatus',
        dictType: 'wms_pd_pdStatus',
        width: 130,
        align: 'left',
      },
      {
        title: t('盘盈亏状态'),
        dataIndex: 'pdStatus',
        dictType: 'wms_pd_yk_status',
        width: 130,
        align: 'left',
      },
      {
        title: t('盘点人'),
        dataIndex: 'pdByName',
        width: 130,
        align: 'left',
      },
      {
        title: t('盘点时间'),
        dataIndex: 'pdDate',
        width: 130,
        align: 'left',
      },
      {
        title: t('行备注'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
      },
    ],
    // actionColumn: {
    //   width: 60,
    //   actions: (record: Recordable) => [
    //     {
    //       label: '明细',
    //       onClick: handleDetail.bind(null, record),
    //       // auth: 'wh:pd:whPdStock:edit',
    //     },
    //   ],
    // },
    rowKey: 'id',
    // pagination: true,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
    showTotalCustomSummary: true,
  });

  // 手动加载表格数据的函数
  async function loadWhPdStocksData() {
    if (!record.value || !record.value.djno) {
      console.log('没有 djno，无法加载表格数据');
      return;
    }

    // if ((record.value as any).isNewRecord) {
    //   console.log('新增记录，不加载表格数据');
    //   return;
    // }

    try {
      console.log('重置分页并加载表格数据，包含 otherData');

      // 重置分页到第一页
      const currentPagination = whPdStocksTable.getPaginationRef();
      const pageSize =
        currentPagination &&
        typeof currentPagination === 'object' &&
        'pageSize' in currentPagination
          ? currentPagination.pageSize
          : page.value;

      whPdStocksTable.setPagination({
        current: 1,
        pageSize: pageSize || page.value,
      });

      // 使用表格的 reload 方法，这样可以正确处理 API 响应中的 otherData
      await whPdStocksTable.reload();
      console.log('表格数据加载完成（包含总计数据，已重置分页）');
    } catch (error) {
      console.error('加载表格数据失败:', error);
    }
  }

  // 查询函数
  async function handleQuery() {
    try {
      queryLoading.value = true;
      // 验证表单
      const formData = await validate();
      console.log('表单验证通过，查询参数:', formData);

      // 删除basWare.cwhname 和 company.companyName
      delete formData.basWare.cwhname;
      delete formData.company.companyName;

      // 调用接口saveByPdType
      const resPdType = await saveByType(formData);
      if ((resPdType as any).result === 'true') {
        // record.value.isNewRecord = false;
        // 重新加载表格数据
        await loadWhPdStocksData();
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('查询错误:', error);
    } finally {
      queryLoading.value = false;
    }
  }

  async function getWhPdStocksList() {
    let whPdStocksListValid = true;
    let whPdStocksList: Recordable[] = [];
    for (const record of whPdStocksTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whPdStocksListValid = false;
      }
      whPdStocksList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of whPdStocksTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whPdStocksList.push({
        ...record,
        status: '1',
      });
    }
    if (!whPdStocksListValid) {
      throw { errorFields: [{ name: ['whPdStocksList'] }] };
    }
    return whPdStocksList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data: any) => {
    setDrawerProps({ loading: true });
    await resetFields();

    // 加载盘点方式字典选项，并禁用值为0的选项
    const dictList = await useDict().initGetDictList('wms_pd_type');
    pdTypeOptions.value = dictList.map((item: any) => ({
      label: item.name,
      value: item.value,
      disabled: item.value === '0',
    }));

    const res = await whPdStockPosBillForm(data);
    record.value = (res.whPdStockPosBill || {}) as WhPdStockPosBill;
    (record.value as any).__t = new Date().getTime();

    // 如果是新建记录且没有设置单据日期，则设置为当天
    if ((record.value as any).isNewRecord && !record.value.ddate) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      // const hours = String(now.getHours()).padStart(2, '0');
      // const minutes = String(now.getMinutes()).padStart(2, '0');
      record.value.ddate = `${year}-${month}-${day}`;
    }

    // 从userStore获取公司编码
    record.value.companyCode = record.value.companyCode
      ? record.value.companyCode
      : userStore.getProjecte.code;
    record.value.companyName = record.value.companyName
      ? record.value.companyName
      : userStore.getProjecte.name;

    // 如果是新建记录且没有设置盘点方式，则设置默认值为2
    if ((record.value as any).isNewRecord && !record.value.pdType) {
      record.value.pdType = '2';
    }

    // 确保 basWare 对象存在，用于仓库字段的回显
    if (record.value.whcode && !(record.value as any).basWare) {
      // 如果有仓库编码但没有 basWare 对象，创建一个基本的对象结构
      (record.value as any).basWare = {
        cwhname: (record.value as any).whname || '', // 使用 whname 字段作为显示名称
      };
    }

    setFieldsValue(record.value);

    // 根据记录类型设置表格数据
    if ((record.value as any).isNewRecord) {
      console.log('新增记录，设置空表格数据并重置分页');
      // 重置分页信息，包括总条数
      whPdStocksTable.setPagination({
        current: 1,
        pageSize: page.value,
        total: 0, // 重置总条数为0
      });
      whPdStocksTable.setTableData([]);
    } else if (record.value.djno) {
      console.log('编辑记录且有 djno，加载表格数据');
      await loadWhPdStocksData();
    } else {
      console.log('编辑记录但没有 djno，设置空表格数据并重置分页');
      // 重置分页信息，包括总条数
      whPdStocksTable.setPagination({
        current: 1,
        pageSize: page.value,
        total: 0, // 重置总条数为0
      });
      whPdStocksTable.setTableData([]);
    }

    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: (record.value as any).isNewRecord,
        id: (record.value as any).id,
      };
      data.whPdStocksList = await getWhPdStocksList();
      // console.log('submit', params, data, record);
      const res = await whPdStockPosBillSave(params, data);
      showMessage((res as any).message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  // 关闭抽屉，刷新父组件
  async function handleCancel() {
    console.log('handleCancel');
    closeDrawer();
    emit('success', { reload: true });
  }
</script>
